package com.zytlifeservice.service.pay;

import com.github.wxpay.sdk.WXPay;
import com.zytlifeservice.config.WxConfig;
import com.zytlifeservice.domain.pay.WxPayOrder;
import com.zytlifeservice.exception.UserException;
import com.zytlifeservice.repository.pay.WxPayOrderRepository;
import com.zytlifeservice.util.TextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by MJS on 2017/6/20.
 */

@Service
public class WxPayService {
    @Value("${wxpay_callback}")
    private String callBackUrl;

    private static final Logger logger = LoggerFactory.getLogger(WxPayService.class);

    @Autowired
    WxPayOrderRepository wxPayOrderRepository;

    @Autowired
    WxConfig wxConfig;

    public String pay(WxPayOrder wxPayOrder) {
        try {
            WXPay wxPay = new WXPay(wxConfig);
            Map<String, String> data = new HashMap<String, String>();

            data.put("body", wxPayOrder.getBody());
            data.put("out_trade_no", wxPayOrder.getOutTradeNo());
            data.put("device_info", wxPayOrder.getStoreId());
            data.put("fee_type", "CNY");
            data.put("total_fee", wxPayOrder.getTotal_fee());
            data.put("spbill_create_ip", wxPayOrder.getSpbill_create_ip());
            data.put("notify_url", callBackUrl);  //自定义callBack
            data.put("trade_type", "NATIVE");  // 此处指定为扫码支付

            logger.info("wx request ={}", data);

            Map<String, String> resp = wxPay.unifiedOrder(data);
            logger.info("wx result ={}", resp);

            String result_code = resp.get("result_code");
            String return_code = resp.get("return_code");

            if (TextUtil.isEmpty(result_code) || !"SUCCESS".equals(result_code) || TextUtil.isEmpty(return_code)
                    || !"SUCCESS".equals(return_code)) {
                wxPayOrder.setOrderStatus(WxPayOrder.ORDER_FAIL);
                wxPayOrderRepository.save(wxPayOrder);
                throw new UserException("微信下单失败", 203);
            }
            wxPayOrder.setOrderStatus(WxPayOrder.ORDER_WAIT);
            wxPayOrderRepository.save(wxPayOrder);
            return resp.get("code_url");
        } catch (Exception e) {
            e.printStackTrace();
        }
        wxPayOrder.setOrderStatus(WxPayOrder.ORDER_FAIL);
        wxPayOrderRepository.save(wxPayOrder);
        throw new UserException("微信下单失败", 203);
    }

    public String refund(WxPayOrder wxPayOrder) {
        return refund(wxPayOrder, "");
    }

    //添加一个金额的功能。
    public String refund(WxPayOrder wxPayOrder, String refund_free) {
        String res = "";
        try {
            WXPay wxpay = new WXPay(wxConfig);
            Map<String, String> data = new HashMap<String, String>();

            data.put("out_trade_no", wxPayOrder.getOutTradeNo());
            String out_refund_no = "zytrefund" + System.currentTimeMillis()   //添加userId
                    + (long) (Math.random() * 10000000L);
            data.put("out_refund_no", out_refund_no);  //退款号重新生成，针对于每一笔的退款
            String price = wxPayOrder.getTotal_fee();
            data.put("total_fee", price);
            if (TextUtil.isEmpty(refund_free)) {
                refund_free = price;
            } else {
                //对于金额做精确到分的处理.
                float parseFloat = Float.parseFloat(refund_free);
                int pPrice = (int) (parseFloat * 100);
                refund_free = String.valueOf(pPrice);
            }
            logger.error("refund amount =" + refund_free);
            data.put("refund_fee", String.valueOf(refund_free));
            data.put("refund_desc", wxPayOrder.getRefundReason());
            logger.info("request data={}", data);
            Map<String, String> refund = wxpay.refund(data);
            logger.info("refund res ={}", refund);
            String return_code = refund.get("return_code");
            if (TextUtil.isEmpty(return_code) || !"SUCCESS".equals(return_code)) {
                wxPayOrder.setRefundStatus(-1);
                wxPayOrderRepository.save(wxPayOrder);
                throw new UserException("微信退款失败，请咨询客服", 2);
            }
            wxPayOrder.setRefundStatus(0);
            res = "微信退款成功";
            wxPayOrderRepository.save(wxPayOrder);
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new UserException("微信退款失败，请咨询客服", 2);
    }
}
